﻿using HirelSeriesH.Global;
using HirelSeriesH.Tools;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Timers;

namespace HirelSeriesH.Entity
{
    /// <summary>
    /// 老化板对应的实体类
    /// </summary>
    public class Channel
    {
        private string iD;
        /// <summary>
        /// 老化板索引号
        /// </summary>
        private int index;
        /// <summary>
        /// 老化板名称
        /// </summary>
        private string channelName;

        private CommPort channelPort;

        /// <summary>
        /// 老化板供电电源ID
        /// </summary>
        private string powerID;
        /// <summary>
        /// 老化板供电电源 
        /// </summary>
        private Power power;

        private VGPower vGPower;

        private List<Power> powerList = new List<Power>();

        /// <summary>
        /// 老化板供电电源ID
        /// </summary>
        private TestParameter testParameter;
        /// <summary>
        /// 保护电阻
        /// </summary>
        private decimal bHDZ;
        /// <summary>
        /// 采样电阻
        /// </summary>
        private decimal cYDZ;
        /// <summary>
        /// 短路报警阈值
        /// </summary>
        private decimal dLYZ;

        /// <summary>
        /// 测试版是否初始化，1=初始化，其它值=不初始化
        /// </summary>
        private decimal toInit = 0;

        /// <summary>
        /// 极性选择：1吸合（05）、0断开（06）
        /// </summary>
        private decimal jXXZ = 0;

        private decimal x3XS = 0;

        private decimal x2XS = 0;

        private decimal x1XS = 0;

        private decimal x0XS = 0;

        /// <summary>
        /// 工位校正K系数
        /// </summary>
        private decimal gWJZ0001_K;
        /// <summary>
        /// 工位校正B常数
        /// </summary>
        private decimal gWJZ0001_B;
        /// <summary>
        /// 工位校正K系数
        /// </summary>
        private decimal gWJZ001_K;
        /// <summary>
        /// 工位校正B常数
        /// </summary>
        private decimal gWJZ001_B;
        /// <summary>
        /// 工位校正K系数
        /// </summary>
        private decimal gWJZ01_K;
        /// <summary>
        /// 工位校正B常数
        /// </summary>
        private decimal gWJZ01_B;

        private decimal gWJZ_K;
        /// <summary>
        /// 工位校正×1B常数
        /// </summary>
        private decimal gWJZ_B;
        /// <summary>
        /// 工位校正×1K系数
        /// </summary>
        private decimal gWJZ1_K;
        /// <summary>
        /// 工位校正×1B常数
        /// </summary>
        private decimal gWJZ1_B;
        /// <summary>
        /// 工位校正×10K系数
        /// </summary>
        private decimal gWJZ10_K;
        /// <summary>
        /// 工位校正×10B常数
        /// </summary>
        private decimal gWJZ10_B;
        /// <summary>
        /// 工位校正×100K系数
        /// </summary>
        private decimal gWJZ100_K;
        /// <summary>
        /// 工位校正×100B常数
        /// </summary>
        private decimal gWJZ100_B;
        /// <summary>
        /// 工位校正×1000K系数
        /// </summary>
        private decimal gWJZ1000_K;
        /// <summary>
        /// 工位校正×1000B常数
        /// </summary>
        private decimal gWJZ1000_B;
        /// <summary>
        /// 测试电阻K系数
        /// </summary>
        private decimal cSDY_K;
        /// <summary>
        /// 测试电阻B常数
        /// </summary>
        private decimal cSDY_B;
        //IR
        private List<string> iRListStr = new List<string>();
        //VR
        private List<string> vRListStr = new List<string>();
        //TJ
        private List<string> tJListStr = new List<string>();
        //PW
        private List<string> pWListStr = new List<string>();

        //IR
        private string iROutPut = "";
        //VR
        private string vROutPut = "";
        //TJ
        private string tJOutPut = "";
        //PW
        private string pWOutPut = "";

        //IR
        private string iROutPutCSV = "";
        //VR
        private string vROutPutCSV = "";
        //TJ
        private string tJOutPutCSV = "";
        //PW
        private string pWOutPutCSV = "";

        //输出电压
        private string outPutVoltCSV = "";
        private string outPutVoltCSV2 = "";
        private string outPutVoltCSV3 = "";
        private string outPutVoltCSV4 = "";
        //输出IR
        private string iROutPutCSVIR = "";

        private bool clearFlag = false;

        private int clearFileFlag = 0;

        /// <summary>
        /// 测试开始时间
        /// </summary> 
        private DateTime startTime;
        /// <summary>
        /// 剩余的测试时长
        /// </summary>
        private TimeSpan testTimeSpan;
        /// <summary>
        /// 测试已进行时长
        /// </summary>
        private TimeSpan runningTime;
        /// <summary>
        /// 老化板工作状态：running（测试运行中）、pause（测试暂停中）、stop（老化板闲置中未工作）
        /// </summary>
        private string state;
        /// <summary>
        /// 测试结束的后续动作
        /// /// </summary>
        private int afterAction = -1;
        /// <summary>
        ///当前老化板是否是正在主界面显示的老化板 
        /// </summary>
        private bool isCurrentChannel;
        /// <summary>
        /// 更新主界面上方运行时间的计时器
        /// </summary>
        private Timer timerForRunTimeLabel;
        /// <summary>
        /// 定时向硬盘文件输出老化板监测数据的计时器
        /// </summary>
        private Timer timerForTestData;
        /// <summary>
        /// 定时向波形文件输出老化板监测数据的计时器
        /// </summary>
        private Timer timerForWaveData;
        /// <summary>
        /// 是否输出数据标志位
        /// </summary>
        private bool outPutFlag = false;

        private List<Position> positions = new List<Position>();

        private string exceptionInfo = "";

        private bool isRed = false;

        private bool waitClose = false;

        private byte[] dataBuffer1;

        private byte[] dataBuffer2;

        private int titleFlag = 0;

        /// <summary>
        /// 老化板的通信地址
        /// </summary>
        private int communityAddress;

        private bool beInit = false;

        public static bool IsClosing1 = false;
        public static bool IsClosing2 = false;

        //子窗口声明定义委托 refresh()
        public delegate void RefreshDelegate();
        public event RefreshDelegate refreshLastTime;
        public event RefreshDelegate refreshExecp;
        public event RefreshDelegate refreshHomeExecp;

        private bool stateEnd = false;

        private PowerPack powerPack;

        private int startTempCycleNumber;

        public Channel(int index)
        {
            Index = index;
            CommunityAddress = index + 176;
            //老化板工作状态
            State = "stop";
            IsCurrentChannel = false;

            for (int i = 0; i < Global.Global.ChannelPositionsCount; i++)
            {
                Position position = new Position(this, i);
                positions.Add(position);

                IRListStr.Add("0");
                VRListStr.Add("0");
                TJListStr.Add("0");
                PWListStr.Add("0");
            }

            TimerForRunTimeLabel = new Timer();
            TimerForRunTimeLabel.Interval = 1000;
            TimerForRunTimeLabel.AutoReset = true;
            TimerForRunTimeLabel.Enabled = false;
            TimerForRunTimeLabel.Elapsed += new ElapsedEventHandler(timerForRunTimeLabel_Tick);

            TimerForTestData = new Timer();
            TimerForTestData.Interval = 1000;
            TimerForTestData.AutoReset = true;
            TimerForTestData.Enabled = false;
            TimerForTestData.Elapsed += new ElapsedEventHandler(TimerForTestData_Tick);

            TimerForWaveData = new Timer();
            TimerForWaveData.Interval = 3000;
            TimerForWaveData.AutoReset = true;
            TimerForWaveData.Enabled = false;
            TimerForWaveData.Elapsed += new ElapsedEventHandler(TimerForWaveData_Tick);

        }

        public string ID { get => iD; set => iD = value; }
        public string ChannelName { get => channelName; set => channelName = value; }
        internal string PowerID { get => powerID; set => powerID = value; }
        internal Power Power { get => power; set => power = value; }
        internal TestParameter TestParameter { get => testParameter; set => testParameter = value; }
        public decimal BHDZ { get => bHDZ; set => bHDZ = value; }
        public decimal CYDZ { get => cYDZ; set => cYDZ = value; }
        public decimal DLYZ { get => dLYZ; set => dLYZ = value; }
        public decimal GWJZ1_K { get => gWJZ1_K; set => gWJZ1_K = value; }
        public decimal GWJZ1_B { get => gWJZ1_B; set => gWJZ1_B = value; }
        public decimal GWJZ10_K { get => gWJZ10_K; set => gWJZ10_K = value; }
        public decimal GWJZ10_B { get => gWJZ10_B; set => gWJZ10_B = value; }
        public decimal GWJZ100_K { get => gWJZ100_K; set => gWJZ100_K = value; }
        public decimal GWJZ100_B { get => gWJZ100_B; set => gWJZ100_B = value; }
        public decimal GWJZ1000_K { get => gWJZ1000_K; set => gWJZ1000_K = value; }
        public decimal GWJZ1000_B { get => gWJZ1000_B; set => gWJZ1000_B = value; }
        public bool IsCurrentChannel { get => isCurrentChannel; set => isCurrentChannel = value; }
        public Timer TimerForRunTimeLabel { get => timerForRunTimeLabel; set => timerForRunTimeLabel = value; }
        public Timer TimerForTestData { get => timerForTestData; set => timerForTestData = value; }
        public DateTime StartTime { get => startTime; set => startTime = value; }
        public string State { get => state; set => state = value; }
        public TimeSpan TestTimeSpan { get => testTimeSpan; set => testTimeSpan = value; }
        public bool OutPutFlag { get => outPutFlag; set => outPutFlag = value; }
        public decimal CSDY_K { get => cSDY_K; set => cSDY_K = value; }
        public decimal CSDY_B { get => cSDY_B; set => cSDY_B = value; }
        public List<Position> Positions { get => positions; set => positions = value; }
        public TimeSpan RunningTime { get => runningTime; set => runningTime = value; }
        public string ExceptionInfo { get => exceptionInfo; set => exceptionInfo = value; }
        public bool IsRed { get => isRed; set => isRed = value; }
        public int Index { get => index; set => index = value; }
        public List<string> IRListStr { get => iRListStr; set => iRListStr = value; }
        public List<string> VRListStr { get => vRListStr; set => vRListStr = value; }
        public List<string> TJListStr { get => tJListStr; set => tJListStr = value; }
        public List<string> PWListStr { get => pWListStr; set => pWListStr = value; }
        public int AfterAction { get => afterAction; set => afterAction = value; }
        public bool WaitClose { get => waitClose; set => waitClose = value; }
        public string IROutPut { get => iROutPut; set => iROutPut = value; }
        public string VROutPut { get => vROutPut; set => vROutPut = value; }
        public string TJOutPut { get => tJOutPut; set => tJOutPut = value; }
        public string PWOutPut { get => pWOutPut; set => pWOutPut = value; }
        public Timer TimerForWaveData { get => timerForWaveData; set => timerForWaveData = value; }
        public bool ClearFlag { get => clearFlag; set => clearFlag = value; }
        public string IROutPutCSV { get => iROutPutCSV; set => iROutPutCSV = value; }
        public string VROutPutCSV { get => vROutPutCSV; set => vROutPutCSV = value; }
        public string TJOutPutCSV { get => tJOutPutCSV; set => tJOutPutCSV = value; }
        public string PWOutPutCSV { get => pWOutPutCSV; set => pWOutPutCSV = value; }
        internal CommPort ChannelPort { get => channelPort; set => channelPort = value; }
        public decimal GWJZ0001_K { get => gWJZ0001_K; set => gWJZ0001_K = value; }
        public decimal GWJZ0001_B { get => gWJZ0001_B; set => gWJZ0001_B = value; }
        public decimal GWJZ001_K { get => gWJZ001_K; set => gWJZ001_K = value; }
        public decimal GWJZ001_B { get => gWJZ001_B; set => gWJZ001_B = value; }
        public decimal GWJZ01_K { get => gWJZ01_K; set => gWJZ01_K = value; }
        public decimal GWJZ01_B { get => gWJZ01_B; set => gWJZ01_B = value; }
        public byte[] DataBuffer1 { get => dataBuffer1; set => dataBuffer1 = value; }
        public byte[] DataBuffer2 { get => dataBuffer2; set => dataBuffer2 = value; }
        public int TitleFlag { get => titleFlag; set => titleFlag = value; }
        public decimal ToInit { get => toInit; set => toInit = value; }
        public decimal X3XS { get => x3XS; set => x3XS = value; }
        public decimal X2XS { get => x2XS; set => x2XS = value; }
        public decimal X1XS { get => x1XS; set => x1XS = value; }
        public decimal X0XS { get => x0XS; set => x0XS = value; }
        public decimal JXXZ { get => jXXZ; set => jXXZ = value; }
        public int CommunityAddress { get => communityAddress; set => communityAddress = value; }
        public bool BeInit { get => beInit; set => beInit = value; }
        public string OutPutVoltCSV { get => outPutVoltCSV; set => outPutVoltCSV = value; }
        public string IROutPutCSVIR { get => iROutPutCSVIR; set => iROutPutCSVIR = value; }
        public string OutPutVoltCSV2 { get => outPutVoltCSV2; set => outPutVoltCSV2 = value; }
        public string OutPutVoltCSV3 { get => outPutVoltCSV3; set => outPutVoltCSV3 = value; }
        public string OutPutVoltCSV4 { get => outPutVoltCSV4; set => outPutVoltCSV4 = value; }
        internal VGPower VGPower { get => vGPower; set => vGPower = value; }
        public decimal GWJZ_K { get => gWJZ_K; set => gWJZ_K = value; }
        public decimal GWJZ_B { get => gWJZ_B; set => gWJZ_B = value; }
        internal List<Power> PowerList { get => powerList; set => powerList = value; }
        public bool StateEnd { get => stateEnd; set => stateEnd = value; }

        public PowerPack PowerPack
        {
            get
            {
                return powerPack;
            }

            set
            {
                powerPack = value;
            }
        }

        public int StartTempCycleNumber
        {
            get
            {
                return startTempCycleNumber;
            }

            set
            {
                startTempCycleNumber = value;
            }
        }

        /// <summary>
        /// 开始测试
        /// </summary>
        public void StartTest()
        {
            /*IRListStr.Clear();
            VRListStr.Clear();
            TJListStr.Clear();
            PWListStr.Clear();

            IROutPut = "";
            VROutPut = "";
            TJOutPut = "";
            PWOutPut = "";

            IROutPutCSV = "";
            VROutPutCSV = "";
            TJOutPutCSV = "";
            PWOutPutCSV = "";

            OutPutVoltCSV = "";
            IROutPutCSVIR = "";

            List<Position> tempList = new List<Position>();
            for (int i = 0; i < 40; i++)
            {
                Position position = new Position(this, i);
                position.ID = positions[i].ID;
                position.ChID = positions[i].ChID;
                position.ChannelName = positions[i].ChannelName;
                position.Index = positions[i].Index;
                position.BasicValue = positions[i].BasicValue;
                tempList.Add(position);

                IRListStr.Add("0");
                VRListStr.Add("0");
                TJListStr.Add("0");
                PWListStr.Add("0");
            }
            positions = tempList;
            ExceptionInfo = "";
            Global.Global.HomeFrom.ExceptionsTextList[Index].Visible = false;
            //Global.Global.HomeFrom.ExceptionsTextList[Index].Width = 0;
            IsRed = false;

            AutoRunBox1.EequeueChannelCommandQueue(new byte[] { 0xAA, (byte)CommunityAddress, 0x05, 0x00, 0x00 });

            if (BeInit)
            {
                System.Threading.Thread.Sleep(9000);
            }
            else
            {
                System.Threading.Thread.Sleep(3000);
            }
            LoadingForm.LoadingHelper.CloseForm();
            UIMessageDialog.ShowMessageDialog(ChannelName + "测试已开始", UILocalize.InfoTitle, false, UIStyle.Colorful);*/
        }

        /// <summary>
        /// 停止测试
        /// </summary>
        public void PauseTest()
        {
            State = "pause";
            StateEnd = false;
            TimerForRunTimeLabel.Enabled = false;
            foreach (var pos in Positions)
            {
                pos.TimerForDirectShort.Stop();
                pos.TimerForShort.Stop();
            }
        }
        /// <summary>
        /// 重置测试状态
        /// </summary>
        public void ResetTest()
        {
            Global.Global.PtcBox.Runned = false;
            Global.Global.PtcBox.Status = "STP";
            StateEnd = false;
            State = "stop";
            RunningTime = new TimeSpan(0, 0, 0);
        }
        /// <summary>
        /// 测试时长计时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerForRunTimeLabel_Tick(object sender, EventArgs e)
        {
            DateTime dateTime = DateTime.Now;
            TimeSpan timeSpan = dateTime - StartTime;
            RunningTime = RunningTime.Add(timeSpan);
            StartTime = dateTime;

            if (Index == 0)
            {
                Debug.WriteLine("Status:" + Global.Global.PtcBox.Status);
                Debug.WriteLine("Runned:" + Global.Global.PtcBox.Runned);
                Debug.WriteLine("ErrorCode:" + Global.Global.PtcBox.ErrorCode);
                Debug.WriteLine("____________________________________");
            }

            if ((Global.Global.PtcBox.Status == "STP" && Global.Global.PtcBox.Runned) || Global.Global.PtcBox.ErrorCode != "NULL")// && Global.Global.PtcBox.IsAtuoClose
            {

                if (Index == 0)
                {
                    Debug.WriteLine("######################################");
                    Debug.WriteLine("Status:" + Global.Global.PtcBox.Status);
                    Debug.WriteLine("Runned:" + Global.Global.PtcBox.Runned);
                    Debug.WriteLine("ErrorCode:" + Global.Global.PtcBox.ErrorCode);
                }

                //State = "pause";
                //StateEnd = true;
                //ClearFlag = true;

                //TimerForRunTimeLabel.Enabled = false;

                /*foreach (var pos in Positions)
                {
                    pos.TimerForDirectShort.Stop();
                    pos.TimerForShort.Stop();
                }*/

                //检测程序自然结束
                //处理电源
                if (PowerPack.IsWork)
                {
                    PowerPack.StopWorkForAuto();
                    if (PowerList[0].TimerForReadData.Enabled)
                    {
                        PowerList[0].TimerForReadData.Stop();
                    }
                    Debug.WriteLine(" PowerPack.StopWorkForAuto():" + Index);
                }

                if (!PowerPack.IsWork)
                {
                    Debug.WriteLine("State Change:" + Index);

                    State = "pause";
                    StateEnd = true;

                    TimerForRunTimeLabel.Enabled = false;

                    foreach (var pos in Positions)
                    {
                        pos.TimerForDirectShort.Stop();
                        pos.TimerForShort.Stop();
                    }

                    //检查是否所有老化板程序都已结束
                    int fg = 0;
                    foreach (var channel in Global.Global.ChannelList)
                    {
                        if (channel.State == "running")
                        {
                            fg = 1;
                            break;
                        }
                    }
                    if (fg != 1)
                    {
                        if (Global.Global.PtcBox.IsOpen)
                        {
                            AutoRun.TimerCheckTemperature.Stop();
                            System.Threading.Thread.Sleep(1000);

                            //Global.Global.PtcBox.IsAtuoClose = false;
                            //关闭
                            string strCommand = "C1=OFF" + "\r\n";
                            Global.Global.BoxPort.Write(strCommand);

                            System.Threading.Thread.Sleep(1000);
                            AutoRun.TimerCheckTemperature.Start();

                            Global.Global.PtcBox.IsOpen = false;
                            Global.Global.ValueBoxRunning = false;
                        }

                        Debug.WriteLine("没有老化板在测试，则将指示灯设置为黄色。");
                        //没有老化板在测试，则将指示灯设置为黄色。
                        if (Global.Global.PlcPort != null && Global.Global.PlcPort.IsOpen)
                        {
                            ThreeColor.EequeueCommandQueue("Yellow");
                        }
                    }
                }

                //没有老化板在测试，则将指示灯设置为黄色。
                /*if (Global.Global.PlcPort != null && Global.Global.PlcPort.IsOpen)
                {
                    ThreeColor.EequeueCommandQueue("Yellow");
                }*/
            }

            if ((Global.Global.PtcBox.Status == "RUN" && Global.Global.PtcBox.Runned) && StartTempCycleNumber > 0)
            {
                int syzqNumber;
                bool canNumber = int.TryParse(Global.Global.Syzq, out syzqNumber);
                if (canNumber)
                {
                    //通道开始时周期-当前温箱周期 - 设定周期小于0视为结束
                    if (testParameter.ChannelTestCycs - (StartTempCycleNumber - syzqNumber) <= 0 && syzqNumber != 0)
                    {

                        //关闭继电器
                        foreach (var pos in Positions)
                        {
                            int powerIndex = Index * Positions.Count + pos.Index;
                            Global.Global.PLC_XINJE.SetDO((byte)powerIndex, false);
                            System.Threading.Thread.Sleep(50);
                        }



                        if (PowerPack.IsWork)
                        {
                            bool isStop = true;
                            foreach (var each in PowerPack.ChannelList)
                            {
                                if (each.index != Index)
                                {
                                    if (each.State == "running")
                                    {
                                        isStop = false;
                                        break;
                                    }
                                }
                            }

                            if (isStop)
                            {
                                PowerPack.StopWorkForAuto();
                                Debug.WriteLine(" PowerPack.StopWorkForAuto():" + Index);
                            }
                            else
                            {

                                Debug.WriteLine("State Change:" + Index);

                                State = "pause";
                                StateEnd = true;

                                TimerForRunTimeLabel.Enabled = false;

                                foreach (var pos in Positions)
                                {
                                    pos.TimerForDirectShort.Stop();
                                    pos.TimerForShort.Stop();
                                }
                            }
                        }

                        if (!PowerPack.IsWork)
                        {
                            Debug.WriteLine("State Change:" + Index);

                            State = "pause";
                            StateEnd = true;

                            TimerForRunTimeLabel.Enabled = false;

                            foreach (var pos in Positions)
                            {
                                pos.TimerForDirectShort.Stop();
                                pos.TimerForShort.Stop();
                            }

                            //检查是否所有老化板程序都已结束
                            int fg = 0;
                            foreach (var channel in Global.Global.ChannelList)
                            {
                                if (channel.State == "running")
                                {
                                    fg = 1;
                                    break;
                                }
                            }
                            if (fg != 1)
                            {
                                if (Global.Global.PtcBox.IsOpen)
                                {
                                    AutoRun.TimerCheckTemperature.Stop();
                                    System.Threading.Thread.Sleep(1000);

                                    //Global.Global.PtcBox.IsAtuoClose = false;
                                    //关闭
                                    string strCommand = "C1=OFF" + "\r\n";
                                    Global.Global.BoxPort.Write(strCommand);

                                    System.Threading.Thread.Sleep(1000);
                                    AutoRun.TimerCheckTemperature.Start();

                                    Global.Global.PtcBox.IsOpen = false;
                                    Global.Global.ValueBoxRunning = false;
                                }

                                Debug.WriteLine("没有老化板在测试，则将指示灯设置为黄色。");
                                //没有老化板在测试，则将指示灯设置为黄色。
                                if (Global.Global.PlcPort != null && Global.Global.PlcPort.IsOpen)
                                {
                                    ThreeColor.EequeueCommandQueue("Yellow");
                                }
                            }
                        }
                    }
                }
            }
        }
        private void TimerForTestData_Tick(object sender, EventArgs e)
        {
            if (testParameter == null)
            {
                return;
            }
            try
            {
                if (State == "running")
                {
                    if (State != "running")
                    {
                        return;
                    }

                    string fileName;
                    string fileNameIR;
                    if (TestParameter.BatchNumber != "")
                    {
                        fileName = "\\" + TestParameter.ProductModel + "-" + TestParameter.BatchNumber + "-C" + (index + 1).ToString() + ".csv";
                        fileNameIR = "\\" + TestParameter.ProductModel + "-" + TestParameter.BatchNumber + "-C" + (index + 1).ToString() + "-Data" + ".csv";
                    }
                    else
                    {
                        fileName = "\\" + TestParameter.ProductModel + "-C" + (index + 1).ToString() + ".csv";
                        fileNameIR = "\\" + TestParameter.ProductModel + "-C" + (index + 1).ToString() + "-Data" + ".csv";
                    }
                    string filePath = "D:\\测试数据";

                    FileStream fileStream;
                    if (!Directory.Exists(filePath))
                    {
                        //创建文本文件夹
                        Directory.CreateDirectory(filePath);
                    }
                    if (!File.Exists(filePath + fileName))
                    {
                        //创建写入文本文件
                        fileStream = new FileStream(filePath + fileName, FileMode.Create);
                        fileStream.Close();
                    }

                    bool isFirstRow = false;
                    FileStream fileStreamIR;
                    if (!File.Exists(filePath + fileNameIR))
                    {
                        //创建写入文本文件
                        fileStreamIR = new FileStream(filePath + fileNameIR, FileMode.Create);
                        fileStreamIR.Close();
                        isFirstRow = true;
                    }

                    string date = DateTime.Now.ToString("yyyy-MM-dd");
                    string time = DateTime.Now.ToLongTimeString();
                    string titleStr = date + "\t" + time + "\t";
                    decimal TJ;
                    TJ = decimal.Parse(Global.Global.CurrenTemperatureStr);
                    string TAStr = "TA(C)\t" + TJ.ToString();
                    string content;
                    string Volt = "电压(V)\t";
                    string Curr = "电流(mA)\t";
                    foreach (var pos in Positions)
                    {
                        Volt = Volt + pos.UValue.ToString() + "\t"; ;
                        Curr = Curr + Math.Round(pos.IValue * 1000, 1).ToString() + "\t"; ;
                    }
                    content =
                      titleStr + Volt + "\r\n"
                    + titleStr + Curr + "\r\n"
                    + titleStr + TAStr + "\r\n"
                    + "======" + "\r\n";

                    fileStream = new FileStream(filePath + fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    StreamWriter swr = new StreamWriter(fileStream, Encoding.Unicode);
                    swr.Write(content);
                    swr.Flush();
                    fileStream.Flush();
                    swr.Close();

                    //IR文件输出
                    if (isFirstRow)
                    {
                        string firstRow = "日期\t时间\t已测时长(小时)\t剩余温度循环周期\t温度\t";
                        for (int i = 1; i <= Positions.Count; i++)
                        {
                            firstRow = firstRow + "#" + i + "电压(V)\t" + "#" + i + "电流(mA)\t";
                        }
                        if (TestParameter.BatchNumber != "")
                        {
                            firstRow = firstRow + "产品型号\t" + "产品批号\t" + "采样间隔\t" + "设定高温\t" + "设定低温\t" + "温箱设定周期\t" + "通道设定周期\t" + "\r\n";
                        }
                        else
                        {
                            firstRow = firstRow + "产品型号\t" + "采样间隔\t" + "设定高温\t" + "设定低温\t" + "温箱设定周期\t" + "通道设定周期\t" + "\r\n";
                        }

                        fileStreamIR = new FileStream(filePath + fileNameIR, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                        StreamWriter swrFirstRow = new StreamWriter(fileStreamIR, Encoding.Unicode);
                        swrFirstRow.Write(firstRow);
                        swrFirstRow.Flush();
                        fileStreamIR.Flush();
                        swrFirstRow.Close();
                    }
                    string Params = "";
                    if (isFirstRow)
                    {
                        if (TestParameter.BatchNumber != "")
                        {
                            Params = TestParameter.ProductModel + "\t" + TestParameter.BatchNumber + "\t" + TestParameter.CheckInterval + "\t" + Global.Global.PtcBox.HighTemp.ToString() + "\t" + Global.Global.PtcBox.LowTemp.ToString() + "\t" + Global.Global.PtcBox.TestCycs.ToString() + "\t" + testParameter.ChannelTestCycs.ToString() + "\t";
                        }
                        else
                        {
                            Params = TestParameter.ProductModel + "\t" + TestParameter.CheckInterval + "\t" + Global.Global.PtcBox.HighTemp.ToString() + "\t" + Global.Global.PtcBox.LowTemp.ToString() + "\t" + Global.Global.PtcBox.TestCycs.ToString() + "\t" + testParameter.ChannelTestCycs.ToString() + "\t";
                        }
                    }
                    double hours = Math.Round(((RunningTime.Days * 24 + RunningTime.Hours) * 3600 + RunningTime.Minutes * 60 + RunningTime.Seconds) / 3600d, 4);
                    string TestTime = hours.ToString();
                    /*int hours = RunningTime.Days * 24 + RunningTime.Hours;
                    string TestTime = hours + "小时" + RunningTime.Minutes.ToString() + "分" + RunningTime.Seconds.ToString() + "秒";*/

                    string titleStrIR = date + "\t" + time + "\t" + TestTime + "\t" + Global.Global.Syzq + "\t" + TJ + "\t";
                    string contentIR;
                    string str = "";
                    foreach (var pos in Positions)
                    {
                        str = str + pos.UValue.ToString() + "\t" + Math.Round(pos.IValue * 1000, 1).ToString() + "\t";
                    }

                    contentIR = titleStrIR + str + Params + "\r\n";

                    fileStreamIR = new FileStream(filePath + fileNameIR, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    StreamWriter swrIR = new StreamWriter(fileStreamIR, Encoding.Unicode);
                    swrIR.Write(contentIR);
                    swrIR.Flush();
                    fileStreamIR.Flush();
                    swrIR.Close();
                }
            }
            catch (Exception ex)
            {
                //Debug.WriteLine(ex.StackTrace);
            }
        }
        private void TimerForWaveData_Tick(object sender, EventArgs e)
        {
            try
            {
                if (State == "running")
                {
                    if (State != "running")
                    {
                        return;
                    }

                    string waveFilePathRoot = "D:\\GRAPHIC";
                    string waveFilePath1 = waveFilePathRoot + "\\GRAPHIC1";
                    FileStream fileStream;
                    if (!Directory.Exists(waveFilePathRoot))
                    {
                        //创建波形根文件夹
                        Directory.CreateDirectory(waveFilePathRoot);
                    }
                    if (!Directory.Exists(waveFilePath1))
                    {
                        //创建波形文件夹
                        Directory.CreateDirectory(waveFilePath1);
                    }
                    //创建波形数据文件
                    for (int i = 1; i <= 8; i++)
                    {
                        if (!File.Exists(waveFilePath1 + ("\\" + i.ToString() + ".dat")))
                        {
                            fileStream = new FileStream(waveFilePath1 + ("\\" + i.ToString() + ".dat"), FileMode.Create);
                            fileStream.Close();
                        }
                    }

                    string date = DateTime.Now.ToString("yyyy-MM-dd");
                    string time = DateTime.Now.ToLongTimeString();
                    string titleStr = date + "\t" + time + "\t";
                    decimal TJ;
                    TJ = decimal.Parse(Global.Global.CurrenTemperatureStr);
                    string TAStr = "TA(C)\t" + TJ.ToString();
                    string content;
                    string Volt = "电压(V)\t";
                    string Curr = "电流(mA)\t";
                    foreach (var pos in Positions)
                    {
                        Volt = Volt + pos.UValue.ToString() + "\t"; ;
                        Curr = Curr + Math.Round(pos.IValue * 1000, 1).ToString() + "\t"; ;
                    }
                    content =
                      titleStr + Volt + "\r\n"
                    + titleStr + Curr + "\r\n"
                    + titleStr + TAStr + "\r\n"
                    + "======" + "\r\n";

                    /*fileStream = new FileStream(waveFilePath1 + ("\\" + (Index + 1).ToString() + ".dat"), FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
                    if (fileStream.Length > 1)
                    {
                        fileStream.SetLength(0);
                        fileStream.Seek(0, SeekOrigin.Begin);
                    }*/
                    fileStream = new FileStream(waveFilePath1 + ("\\" + (Index + 1).ToString() + ".dat"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    StreamWriter swr = new StreamWriter(fileStream, Encoding.Unicode);
                    swr.Write(content);
                    swr.Flush();
                    fileStream.Flush();
                    swr.Close();
                }
            }
            catch (Exception ex)
            {
                //Debug.WriteLine(ex.StackTrace);
            }
        }
        /// <summary>
        /// 短路报警及保护措施
        /// </summary>
        /// <param name="address"></param>
        /// <param name="pos"></param>
        public void directShort(int address, int pos)
        {
            IsRed = true;
            Positions[pos].IsShort = true;

            ExceptionInfo = ExceptionInfo + (address + 1).ToString() + "号老化板" + (pos + 1).ToString() + "测试位疑似短路；";
            refreshHomeExecp();

            if (isCurrentChannel)
            {
                Global.Global.ExecInfo = ExceptionInfo;
                refreshExecp();
                Global.Global.LabelArrayIR[pos].BackColor = Color.Red;
                Global.Global.LabelArrayIR[pos].Text = "断开";
                Global.Global.LabelArrayVR[pos].BackColor = Color.Red;
            }
            if (Global.Global.Buttons.Count == 4)
            {
                Global.Global.Buttons[address].FillColor = Color.Red;
                Global.Global.Buttons[address].FillColor2 = Color.Red;
                //Global.Global.Buttons[address].UseVisualStyleBackColor = false;
            }
            //设置电压为0
            Power.setVolt(0);
            //休眠100毫秒
            //System.Threading.Thread.Sleep(100);
            //关闭电源输出
            Power.close();
            Power.IsOpen = false;
            Power.IsUpDown = false;
            Power.RealVoltage = 0;
            Power.RealCurrent = 0;

            System.Threading.Thread.Sleep(1000);
            //发送老化板停止运行指令
            AfterAction = 4;
            //AutoRunBox1.EequeueChannelCommandQueue(new byte[] { 0xAA, (byte)CommunityAddress, 0x01, 0x00, 0x00 });
            //指示灯报警
            ThreeColor.EequeueCommandQueue("Red");
        }
        /// <summary>
        /// 过流报警
        /// </summary>
        /// <param name="address"></param>
        /// <param name="pos"></param>
        public void IRRed(int address, int pos, string WorkType)
        {
            if (Positions[pos].IsOver)
            {
                return;
            }

            Positions[pos].IsOver = true;
            IsRed = true;
            ExceptionInfo = ExceptionInfo + (address + 1).ToString() + "号老化板" + (pos + 1).ToString() + "测试位电流报警；";
            refreshHomeExecp();

            if (isCurrentChannel)
            {
                Global.Global.ExecInfo = ExceptionInfo;
                refreshExecp();
                Global.Global.LabelArrayIR[pos].BackColor = Color.Red;
                Global.Global.LabelArrayIR[pos].Text = "过流";
                Global.Global.LabelArrayVR[pos].BackColor = Color.Red;
            }
            if (Global.Global.Buttons.Count == 4)
            {
                Global.Global.Buttons[address].FillColor = Color.Red;
                Global.Global.Buttons[address].FillColor2 = Color.Red;
                //Global.Global.Buttons[address].UseVisualStyleBackColor = false;
            }

            if (power.IsUpDown)
            {
                Power.StopUp = true;
            }
            if (power.IsTest)
            {
                Power.AC = "Test";
            }
            Power.TimerUp.Stop();
            Power.TimerDown.Stop();
            power.IsUpDown = false;

            //设置电压为0
            Power.setVolt(0);
            //休眠100毫秒
            System.Threading.Thread.Sleep(1000);
            //关闭电源输出
            Power.close();
            Power.IsOpen = false;
            Power.IsUpDown = false;
            Power.RealVoltage = 0;
            Power.RealCurrent = 0;
            power.VoltageCurrent = 0;

            System.Threading.Thread.Sleep(1000);

            //发送老化板停止运行指令
            /*if (WorkType == "S")
            {
                AutoRunBox1.EequeueChannelCommandQueue(new byte[] { 0xAA, (byte)CommunityAddress, 0x0E, 0x00, (byte)pos });
            }
            else
            {
                AutoRunBox1.EequeueChannelCommandQueue(new byte[] { 0xAA, (byte)CommunityAddress, 0x0E, 0x00, (byte)(pos * 5) });
                AutoRunBox1.EequeueChannelCommandQueue(new byte[] { 0xAA, (byte)CommunityAddress, 0x0E, 0x00, (byte)(pos * 5 + 1) });
                AutoRunBox1.EequeueChannelCommandQueue(new byte[] { 0xAA, (byte)CommunityAddress, 0x0E, 0x00, (byte)(pos * 5 + 2) });
                AutoRunBox1.EequeueChannelCommandQueue(new byte[] { 0xAA, (byte)CommunityAddress, 0x0E, 0x00, (byte)(pos * 5 + 3) });
                AutoRunBox1.EequeueChannelCommandQueue(new byte[] { 0xAA, (byte)CommunityAddress, 0x0E, 0x00, (byte)(pos * 5 + 4) });
            }*/
        }

        /*public void powerAutoUp()
        {
            System.Threading.Thread.Sleep(60000);
            if ((State == "running") && (!Power.IsOpen))
            {
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(Power.powerAutoUp));
                thread.Start();
            }
        }*/

    }
}
